from django.core.exceptions import ObjectDoesNotExist
from rest_framework import viewsets, status
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.response import Response
from rest_framework.decorators import action

from account.models import Profile
from movie.models import Movie
from movie.serializers import MovieSerializer


# Create your views here.
class CollectViewSet(viewsets.ModelViewSet):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer
    permission_classes = [IsAuthenticated]

    def get_permissions(self):
        if self.request.method in ['PUT', 'PATCH']:
            return [IsAdminUser()]
        return [IsAuthenticated()]

    def list(self, request, *args, **kwargs):
        user = request.user
        profile = Profile.objects.get(user=user)
        # 定义你想要展示的字段
        movies = profile.movies.all()
        data = movies.values('id', 'movie_name')
        print(data)

        serializer = MovieSerializer(movies, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
        # return Response({'message': 'ok', 'data': data})

    def create(self, request, *args, **kwargs):
        user = request.user
        profile = Profile.objects.get(user=user)
        movie_id = request.data['movie_id']
        try:
            movie = Movie.objects.get(id=movie_id)
            profile.movies.add(movie)
            return Response({'code': 1000, 'message': '收藏成功'})
        except ObjectDoesNotExist:
            return Response({'code': 1001, 'message': '电影信息不存在'})
        except Exception as e:
            return Response({'code': 1002, 'message': '收藏失败', 'error': str(e)})

    def destroy(self, request, *args, **kwargs):
        """
        def destroy(self, request, pk): x <= 不建议
        为了消除警告并确保代码的可读性和一致性，建议使用 *args 和 **kwargs 的方式。
        通过这种方式，你可以保持与基类 DestroyModelMixin 的签名一致，避免警告，
        同时仍然能够处理 pk 参数。
        """
        pk = kwargs.get('pk')
        print(pk, 'pk')
        user = request.user
        profile = Profile.objects.get(user=user)
        try:
            movie = Movie.objects.get(id=pk)
            if movie not in profile.movies.all():
                return Response({'message': '未收藏该电影'})
            profile.movies.remove(movie)
            return Response({'code': 1000, 'message': '取消收藏成功'})
        except ObjectDoesNotExist:
            return Response({'code': 1001, 'message': '电影信息不存在'})
        except Exception as e:
            print({str(e)})
            return Response({'code': 1002, 'message': f'取消收藏失败'})

    @action(detail=True, methods=['get'])
    def is_collected(self, request, pk=None):
        user = request.user
        profile = Profile.objects.get(user=user)
        movie = Movie.objects.get(id=int(pk))
        is_collected = profile.movies.filter(id=int(movie.id)).exists()
        return Response({'is_collected': is_collected})
